package com.offcn.test;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * 通过版本(印记)解决ABA问题(B将n改为2后又改为1,CAS判断true)
 */
public class CASTest3 {
    public static void main(String[] args) throws Exception {
        long l1 = System.currentTimeMillis();
        AtomicStampedReference<Integer> asr = new AtomicStampedReference<>(1, 1);
        new Thread(() -> {
            //修改数据
            //取出当前值
            int ex = asr.getReference();
            int n = ex + 1;
            //取出当前的印记(版本)
            int stamp = asr.getReference();
            int newStamp = stamp + 1;
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            boolean b = asr.compareAndSet(ex, n, stamp, newStamp);
            System.out.println("修改:"+b);
        }).start();
        asr.compareAndSet(asr.getReference(), asr.getReference() + 1, asr.getStamp(), asr.getStamp() + 1);
        System.out.println("n="+asr.getReference());
        asr.compareAndSet(asr.getReference(), asr.getReference() - 1, asr.getStamp(), asr.getStamp() + 1);
        System.out.println("n="+asr.getReference());
    }
}